package com.cmge.ad.util.listener;

import com.cmge.ad.util.config.CompositeFactory;
import com.cmge.ad.util.context.ServletContextUtil;
import com.cmge.ad.util.thread.*;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;

/**
 * @desc	系统监听器
 * @author	ljt
 * @time	2014-6-23 下午5:17:22
 */
public class SystemListener implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent event) {

	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		initConfig(event);
		try {
			initLog(event);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ServletContextUtil.setContext(event.getServletContext());

//		initThread();
	}

	private void initThread() {
		Thread t1 = new Thread(new SyncArticle());
		t1.start();

		Thread t2 = new Thread(new SyncAlbum());
		t2.start();

		Thread t3 = new Thread(new CrawlerMonitor());
		t3.start();

		Thread t4 = new Thread(new AutoSyncArticle());
		t4.start();

		Thread t5 = new Thread(new AutoCrawlArticle());
		t5.start();
	}

	private void initConfig(ServletContextEvent event) {
		// 读取主配置文件  这里可以把properties和xml配置文件统一放在一个xml中，遍历加载
		try {
			PropertiesConfiguration propertiesConfiguration1 = new PropertiesConfiguration("resultCode.properties");
			PropertiesConfiguration propertiesConfiguration2 = new PropertiesConfiguration("systemConfig.properties");
			CompositeFactory.getInstance().addConfiguration(propertiesConfiguration1);
			CompositeFactory.getInstance().addConfiguration(propertiesConfiguration2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initLog(ServletContextEvent event) throws IOException {
		ServletContext context = event.getServletContext();
		String log4jParam = context.getInitParameter("log4jPath");
		String log4jPath = context.getRealPath(log4jParam);

		ServletContext servletContext = event.getServletContext();
		// Only perform custom log4j initialization in case of a config file.
		String location = servletContext.getInitParameter("log4jPath");
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		//只加载一个绝对匹配Resource，且通过ResourceLoader.getResource进行加载
		Resource resource = resolver.getResource(location);

		Thread thread = new Thread(new LoadLogFile(resource.getFile().getPath()));
		thread.start();
	}
}
